<!-- eslint-disable prettier/prettier -->
<template>
  <div class="conetr" :loading="loading">
    <div class="center-board">
      <div class="center-title">
        <h3>代金券申请</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button icon="Download" type="success" plain @click="submitForm">保存</el-button>
      </div>
    </div>
    <div class="center-form">
      <el-form ref="formRef" :model="applyForm" :rules="rules" label-width="100px">
        <div class="form-flex">
          <div>我的积分：{{ infos?.merPointsSummary.points }}</div>
          <div>额度：{{ infos?.merPointsSummary.quotas }}</div>
          <div>积分：现金=10:1</div>
        </div>
        <el-form-item label="类型" prop="type" class="form-item" required>
          <el-select
            v-model="applyForm.type"
            placeholder="请选择"
            filterable
            @change="changeTitle(applyForm.type, 'type')"
          >
            <el-option v-for="item in types" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="品类"
          prop="supportedCategoryId"
          class="form-item"
          :rules="{
            required: true,
            message: '请选择品类',
            trigger: 'change',
          }"
        >
          <el-radio-group
            v-model="applyForm.supportedCategoryId"
            @change="changeTitle(applyForm.supportedCategoryId, 'supportedCategory')"
          >
            <el-radio v-for="item in categoryList" :key="item.id" :value="item.id">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="infos?.userType == 'MC03' && manageList.length > 0"
          label="品牌"
          prop="brandId"
          class="form-item"
        >
          <!-- :rules="{
            required: true,
            message: '请选择品牌',
            trigger: 'change',
          }" -->
          <el-radio-group
            v-model="applyForm.brandId"
            @change="changeTitle(applyForm.brandId, 'brandName')"
          >
            <el-radio v-for="item in manageList" :key="item.id" :value="item.id">
              {{ item.brandName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="title" class="form-item">
          <el-input v-model="applyForm.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="券额" prop="amount" class="form-item">
          <el-input
            v-model="applyForm.amount"
            type="number"
            placeholder="请输入"
            :min="0"
            @change="changeInput"
          >
            <template #append>积分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="totalStorage" class="form-item">
          <el-input
            v-model="applyForm.totalStorage"
            type="number"
            placeholder="请输入"
            :min="0"
            @change="changeInput"
          />
        </el-form-item>
        <el-form-item label="兑换时间" prop="conversionTime" class="form-item">
          <el-date-picker
            v-model="applyForm.conversionTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="可用时间" prop="usableTime" class="form-item">
          <el-date-picker
            v-model="applyForm.usableTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <!-- <el-form-item
          label="支付凭证"
          prop="files"
          class="form-item"
          :rules="{
            required: true,
            message: '请上传凭证',
            trigger: 'change',
          }"
        >
          <ImageUpload v-model="applyForm.files" :limit="1" />
        </el-form-item> -->
        <!-- <el-form-item label="预算范围" prop="budgetMin" class="form-item">
          <el-col :span="11">
            <el-input v-model="applyForm.budgetMin" type="number" placeholder="请输入" />
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-input v-model="applyForm.budgetMax" type="number" placeholder="请输入" />
          </el-col>
        </el-form-item> -->
        <!-- <el-form-item label="支付积分" class="form-item" required>
          <el-input v-model="sumTotal" type="number" placeholder="请输入" disabled />
        </el-form-item> -->
        <!-- <div class="ms">
          <div>额度:(券额*10)*数量=(300*10)*10=30000</div>
          <div>加工费:已消耗额度*比例=30000*20%=6000</div>
          <div>支付积分:已消耗额度+加工费=30000+6000=36000</div>
        </div> -->
      </el-form>
    </div>
  </div>
</template>

<script setup>
import ImageUpload from "@/components/ImageUpload/index.vue";
import UserAPI from "@/api/system/user";
import couponApi from "@/api/coupon/coupon";

const emit = defineEmits(["update:dialogShow", "refreshList", "backTo"]);
const applyForm = ref({
  id: undefined,
  type: 1,
  brandId: undefined,
  title: "",
  amount: undefined,
  totalStorage: undefined,
  files: undefined,
  startEffectiveTime: "",
  endEffectiveTime: "",
  publishTime: "",
  archiveTime: "",
  supportedCategoryId: undefined,
  conversionTime: undefined,
  usableTime: undefined,
  budgetMin: undefined,
  budgetMax: undefined,
});
const infos = ref();
const sumTotal = ref();
const loading = ref(false);
const selectName = ref({
  brandName: "",
  type: "",
  supportedCategory: "",
});
const types = ref([
  {
    name: "到店礼",
    id: 1,
  },
  // {
  //   name: "补贴券",
  //   id: 2,
  // },
]);
const rules = ref({
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  title: [{ required: true, message: "请输入名称", trigger: "change" }],
  amount: [{ required: true, message: "请输入券额", trigger: "change" }],
  totalStorage: [{ required: true, message: "请输入数量", trigger: "change" }],
  // budgetMin: [
  //   { required: true, message: "请输入预算范围", trigger: "change" },
  //   {
  //     validator: (rule, value, callback) => {
  //       if (value && applyForm.value.budgetMin && value > applyForm.value.budgetMax) {
  //         callback(new Error("预算值有误"));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: "change",
  //     message: "预算值有误",
  //   },
  // ],
  conversionTime: [{ required: true, message: "请选择兑换日期", trigger: "change" }],
  usableTime: [{ required: true, message: "请选择可用日期", trigger: "change" }],
});
const categoryList = ref([]); //品类
const manageList = ref([]); //品牌
const formRef = ref();

const loadUserProfile = async () => {
  const data = await UserAPI.getProfile();
  infos.value = data.data;
  if (
    infos.value.merchantCompany?.categoryIds != "" ||
    infos.value.merchantCompany?.categoryIds != null
  ) {
    const categoryId = infos.value.merchantCompany.categoryIds.split(",").reduce((acc, curr) => {
      acc.push(Number(curr));
      return acc;
    }, []);
    const categoryName = infos.value.merchantCompany.categoryNames.split(",");
    for (let i = 0; i < categoryId.length; i++) {
      categoryList.value.push({ name: categoryName[i], id: categoryId[i] });
    }
  }
  // if (
  //   infos.value.merchantCompany?.manageBrandIds &&
  //   infos.value.merchantCompany?.manageBrandIds != ""
  // ) {
  //   const manageBrandIds = infos.value.merchantCompany.manageBrandIds
  //     .split(",")
  //     .reduce((acc, curr) => {
  //       acc.push(Number(curr));
  //       return acc;
  //     }, []);
  //   const manageBrandText = infos.value.merchantCompany.manageBrandText.split(",");
  //   for (let i = 0; i < manageBrandIds.length; i++) {
  //     manageList.value.push({ name: manageBrandText[i], id: manageBrandIds[i] });
  //   }
  // }
};
function changeTitle(id, name) {
  if (name == "type") {
    selectName.value[name] = types.value.filter((item) => item.id === id)[0].name;
  } else if (name == "supportedCategory") {
    selectName.value[name] = categoryList.value.filter((item) => item.id === id)[0].name;
    applyForm.value.brandId = undefined;
    getBrandList(id);
  } else if (name == "brandName") {
    selectName.value[name] = manageList.value.filter((item) => item.id === id)[0].brandName;
  }
  if (selectName.value.type != "" && selectName.value.supportedCategory != "") {
    applyForm.value.title =
      selectName.value.type + "-" + selectName.value.supportedCategory + selectName.value.brandName;
  } else {
    applyForm.value.title = "";
  }
}

async function getBrandList(id) {
  try {
    const res = await couponApi.getBrandList(id);
    manageList.value = res.data;
  } catch (e) {}
}
function backTo() {
  emit("backTo");
}

function changeInput() {
  if (applyForm.value.amount && applyForm.value.totalStorage) {
    sumTotal.value = Number(applyForm.value.amount) * Number(applyForm.value.totalStorage);
  } else {
    sumTotal.value = undefined;
  }
}

async function submitForm() {
  const validates = await formRef.value.validate();
  let titles = "";
  const names = {
    1: "到店礼",
    2: "补贴券",
  };
  if (applyForm.value.type == 2) {
    titles = "确定发布吗？";
  } else {
    if (
      sumTotal.value > infos.value.merPointsSummary.points &&
      sumTotal.value < infos.value.merPointsSummary.points + infos.value.merPointsSummary.quotas
    ) {
      const points = sumTotal.value - infos.value.merPointsSummary.points;
      titles = `发行数量超出可使用消耗额度,超出的部分会扣除${points}的积分,确定继续发行这套${names[applyForm.value.type]}吗？`;
    } else if (
      sumTotal.value >
      infos.value.merPointsSummary.points + infos.value.merPointsSummary.quotas
    ) {
      ElMessageBox.confirm(
        "发行总券额超出可使用消耗额度与积分，暂时无法发布，请先充值积分",
        "提示",
        { type: "warning" }
      );
      return;
    } else {
      titles = `确定消耗${sumTotal.value}额度发行这套${names[applyForm.value.type]}吗？`;
    }
  }
  if (validates) {
    ElMessageBox.confirm(titles, "提示", {
      type: "warning",
    }).then(async () => {
      let data = JSON.parse(JSON.stringify(applyForm.value));
      data.claimStartTime = data.conversionTime[0];
      data.claimEndTime = data.conversionTime[1];
      data.effectiveStartTime = data.usableTime[0];
      data.effectiveEndTime = data.usableTime[1];
      loading.value = true;
      await couponApi
        .addStorage(data)
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            emit("backTo", true);
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  }
}

onMounted(() => {
  loadUserProfile();
  if (!applyForm.value.id) {
    changeTitle(1, "type");
  }
});
</script>
<style scoped lang="scss">
.conetr {
  padding: 10px;
  background-color: #fff;
  position: relative;
  flex: 1;
  margin-left: 10px;
  box-sizing: border-box;
  background-color: #fff;
  padding: 10px 20px;
  .center-board {
    .center-title {
      position: absolute;
      left: 20px;
    }
    .action-bar {
      position: relative;
      box-sizing: border-box;
      padding: 10px 0 15px 0;
      border-bottom: 1px solid var(--el-border-color-extra-light);
      display: flex;
      align-items: center;
      justify-content: flex-end;

      u .delete-btn {
        color: #f56c6c;
      }
    }
  }
  .center-form {
    .form-flex {
      width: 600px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      padding-left: 40px;
    }
    .form-item {
      width: 600px;
    }
    .ms {
      padding-left: 20px;
      color: #999;
    }
  }
}
</style>
